<template>
  <div class="container">

    <div class="filter-container machine-group">
      <el-input
        v-model="dataForm.setName"
        placeholder="请输入测试集名称"
        size="medium"
        style="width: 200px; margin-right: 10px;"
        class="filter-item"
        @keyup.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-plus" size="medium" @click="createHandle">
        添加测试集
      </el-button>
      <el-dropdown @command="batchHandle">
        <el-button type="danger" size="medium" class="filter-item">
          批量操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="addToPlan">添加到测试计划</el-dropdown-item>
          <el-dropdown-item command="batchDel">批量删除</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshHandle">
        刷新
      </el-button>
      <el-button class="filter-item export" type="success" icon="el-icon-download" size="medium" @click="exportExcelHandle">
        导出
      </el-button>
    </div>
    <el-table
      border
      highlight-current-row
      :data="pageData"
      style="width: 100%"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="set_name"
        align="center"
        :show-overflow-tooltip="true"
        label="测试集名称"
        min-width="180"
      />
      <el-table-column
        prop="case_count"
        sortable
        align="center"
        min-width="100"
        label="测试用例"
      >
        <template slot-scope="{ row }">
          <router-link :to="{ path: '/caseSet/caseSetManager/' + row.id + '/' + row.set_name}">
            <el-tag class="step-count">{{ row.case_count === '' ? 0:row.case_count }}</el-tag>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        sortable
        align="center"
        min-width="140"
        label="创建时间"
      />
      <el-table-column
        prop="creator_name"
        align="center"
        label="创建人"
      />
      <el-table-column
        prop="mark"
        align="center"
        :show-overflow-tooltip="true"
        min-width="180"
        label="备注"
      />
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="120">
        <template v-if="scope.row.id != 1" slot-scope="scope">
          <el-button type="text" size="small" @click="editHandle(scope.row,0)">编辑</el-button>
          <el-button type="text" size="small" @click="editHandle(scope.row,1)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 测试集编辑弹出框 -->
    <CaseSetDialog
      v-if="showDialog"
      :case-set-item="caseSetItem"
      @closeDialog="closeDialog"
    />

    <!--添加到测试计划-->
    <el-dialog
      title="请选择测试计划（可选多个）"
      :visible.sync="testPlan.visible"
      width="45%"
      :close-on-click-modal="false"
      :center="true"
    >
      <el-row :gutter="10" type="flex">
        <el-col :span="16">
          <el-select v-model="testPlan.value" filterable style="width: 100%" multiple size="medium" placeholder="可搜索测试计划">
            <el-option
              v-for="item in testPlan.list"
              :key="item.id"
              :label="item.plan_name"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="medium" @click="addSetToPlan">确定</el-button>
          <el-button size="medium" @click="testPlan.visible = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import CaseSetDialog from './component/CaseSetDialog.vue'
import { testplenList, addHandleList } from '@/api/testplan'
import { listCaseSet, delCasesSetInfo } from '@/api/caseSet'
import { exportExcel1 } from '@/utils/exportExcelUtils'
import { batchHandle } from '@/utils/commonUtil'

export default {
  name: 'CaseSet',
  components: {
    CaseSetDialog
  },
  data() {
    return {
      tableData: [],
      selectIds: [],
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      showDialog: false,
      caseSetItem: {
        id: undefined,
        set_name: '',
        mark: '',
        status: ''
      },
      testPlan: {
        list: [],
        visible: false,
        value: []
      },
      dataForm: {
        setName: ''
      }
    }
  },
  computed: {
    locationBy() {
      return this.$store.state.user.dictConfig.locationBy
    },
    elementType() {
      return this.$store.state.user.dictConfig.elementType
    },
    // 总数
    total() {
      return this.tableData.length
    },
    // 当前分页数据
    pageData() {
      return this.tableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    }

  },
  watch: {
    tableData() {
      this.pageIndex = 1
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 详细的过滤操作，需要覆写此方法
    selfHandleFilter(data) {
      if (this.dataForm.setName !== '') {
        data = data.filter(item => item.set_name.indexOf(this.dataForm.setName) !== -1)
      }
      if (this.dataForm.setName === '') {
        this.getData()
      }
      return data
    },
    selectRowHandle(selection) {
      this.selectIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectIds.push(row.id)
      })
    },
    handleFilter() {
      const data = []
      Object.assign(data, this.tableData)
      this.tableData = this.selfHandleFilter(data)
    },
    // 表格排序
    tableSortChange({ column, prop, order }) {
      this.tableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    refreshHandle() {
      this.getData()
    },
    createHandle() {
      this.caseSetItem = {
        id: undefined,
        set_name: '',
        mark: '',
        status: 'create'
      }
      this.showDialog = true
    },
    editHandle(row, state) {
      // 编辑
      if (state === 0) {
        this.caseSetItem = {
          id: row.id,
          set_name: row.set_name,
          mark: row.mark,
          status: 'update'
        }
        this.showDialog = true
      } else { // 删除
        this.$confirm('确认要删除【' + row.set_name + '】测试集吗  ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCasesSetInfo({ id: row.id }).then(response => {
            this.getData()
            this.$message.success('删除成功')
          })
        }).catch(() => {
        })
      }
    },
    // 关闭组名edit操作
    closeDialog(flag) {
      if (flag) {
        // 重新刷新表格内容
        this.getData()
      }
      this.showDialog = false
    },
    getData() {
      const params = {}
      listCaseSet(params).then(response => {
        this.tableData = response.data
      })
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    exportExcelHandle() {
      const tHeader = ['ID', '测试集名称', '测试用例', '创建时间', '创建人', '备注']// 上面设置Excel的表格第一行的标题
      const filterVal = ['id', 'set_name', 'case_count', 'create_time', 'creator_name', 'mark'] // 上面的index、nickName、name是tableData里对象的属性
      const list = this.tableData // 把data里的tableData存到list
      const excelName = '测试集'
      exportExcel1(tHeader, filterVal, list, excelName)
    },
    batchHandle(command) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      if (command === 'batchDel') {
        this.batchDelHandle()
      }
      if (command === 'addToPlan') {
        testplenList().then(response => {
          this.testPlan.list = response.data
          this.testPlan.value = []
          this.testPlan.visible = true
        })
      }
    },
    // 添加指定数据到测试计划
    addSetToPlan() {
      if (this.testPlan.value.length === 0) {
        this.$message.warning('请选择至少一个测试计划')
        return false
      }
      const that = this
      batchHandle({
        vm: that,
        vmNotify: true,
        opName: '添加',
        data: this.testPlan.value,
        opHandle: function(val, resolve, reject) {
          addHandleList({ plan_id: val }, that.selectIds).then(() => {
            resolve()
          }).catch(() => {
            reject()
          })
        },
        finishCallback(successCount, failCount) {
          // 防止一些新增的步骤没有ID 导致排序不成功
          that.testPlan.visible = false
        }// 完成之后的回调
      })
    },
    batchDelHandle() {
      let failCount = 0
      const self = this
      this.$confirm('是否批量删除选择的共 ' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectIds.forEach(function(val) {
          delCasesSetInfo({ id: val }).then(response => {
          }).catch(() => {
            failCount++
          })
        })
        const intervalId = setInterval(function() {
          self.getData()
          clearInterval(intervalId)
          if (failCount === 0) {
            self.$notify({
              title: '通知',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            self.$notify({
              title: '通知',
              message: '共' + failCount + '条数据删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }, 300)
      }).catch()
    }
  }
}
</script>

<style scoped>
  .machine-group {
    margin: 20px 0px 0px 0px;
  }

  .container {
    padding-left: 25px;
    padding-right: 25px;
  }
  .export{
    float: right;
  }
</style>
